package cn.tradewin.advisor.components.general;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Events;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.ajax.AjaxResponseRenderer;

import cn.tradewin.advisor.commons.selectmodel.CodeLabelSelectModel;
import cn.tradewin.advisor.persist.model.Department;
import cn.tradewin.advisor.persist.services.AccountService;
import cn.tradewin.advisor.persist.services.DeptService;

@Events({ AddDept.CANCELED, AddDept.ADD })
public class AddDept {
	public static final String CANCELED = "canceled";
	public static final String ADD = "add";

	@Property
	private Department dept;

	@Property
	private SelectModel deptOwnerModel;
	
	@Inject
	private AccountService accountService;
	
	@Inject
	private DeptService deptService;

	@InjectComponent
	private Form form;

	@InjectComponent
	private Zone formZone;

	@Inject
	private Request request;

	@Inject
	private ComponentResources componentResources;

	@Inject
	private AjaxResponseRenderer ajaxResponseRenderer;

	void onPrepareForRender() {
		deptOwnerModel = new CodeLabelSelectModel(accountService.getAccountsOptions());
	}
	
	void onPrepare() {
		if (dept == null) {
			dept = new Department();
		}
	}

	boolean onCancel() {
		componentResources.triggerEvent(CANCELED, new Object[] {}, null);
		return true;
	}

	boolean onSuccess() {
		componentResources.triggerEvent(ADD, new Object[] { dept }, null);
		return true;
	}

	boolean onFailure() {
		if (request.isXHR()) {
			ajaxResponseRenderer.addRender(formZone);
		}
		return true;
	}

	boolean onValidateFromForm() {
		if (form.getHasErrors()) {
			return true;
		}
		try {
			deptService.addDept(dept);
		} catch (Exception e) {
			form.recordError(e.getMessage());
		}
		return true;
	}
}
